package weiyao.xinxidasai.Utils.FaceToken;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.util.Base64Util;

import org.json.JSONObject;
import weiyao.xinxidasai.Utils.Encryption.Chaos.FileUtil;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


public class FaceDetection {
    public static final String APP_ID = "119048175";
    public  static final String API_KEY = "Xmr7B8L67QICY4FHFhLP9NZ7";
    public  static final String SECRET_KEY = "fU4ufPPYQCUU4ofhH27OFYFynsU5gOZv";
    // 阈值配置
    private static final double MIN_FACE_PROBABILITY = 0.95;
    private static final double MAX_ANGLE = 15.0;
    private static final double POSITION_THRESHOLD = 0.05;
    private static final double OCCLUSION_THRESHOLD = 0.5;
    private static final double MIN_ILLUMINATION = 50.0;
    private static final double MAX_ILLUMINATION = 200.0;
    private static final double MAX_BLUR = 0.3;
    private static final double MIN_EYE_STATUS = 0.7;
    public static Map<String, Object> validateFaceDetection(File imageFile) throws IOException {
        // 读取图片文件并获取尺寸
        BufferedImage image = ImageIO.read(imageFile);
        int imageWidth = image.getWidth();
        int imageHeight = image.getHeight();

        // 将图片转换为Base64
        String imageBase64 = Base64Util.encode(FileUtil.readFileByBytes(imageFile.getAbsolutePath()));

        // 调用百度API获取人脸检测结果
        JSONObject faceResult = getJsonObject(imageBase64);

        Map<String, Object> result = new HashMap<>();
        int successCount = 0;

        // 1. 检查人脸数量
        if (!faceResult.has("result") || faceResult.getJSONObject("result").getInt("face_num") == 0) {
            result.put("face_num", "图片中无人脸");
        } else {
            result.put("face_num", "图片中人脸数目为1，通过检测");
            successCount++;}

            JSONObject face = faceResult.getJSONObject("result").getJSONArray("face_list").getJSONObject(0);

        double faceProbability = face.optDouble("face_probability", 0);
        result.put("face_probability", faceProbability);  // 直接返回数值
        if (faceProbability >= MIN_FACE_PROBABILITY) {
            successCount++;
        }
            // 3. 检查角度
            JSONObject angle = face.getJSONObject("angle");
            if (Math.abs(angle.getDouble("yaw")) > MAX_ANGLE ||
                    Math.abs(angle.getDouble("pitch")) > MAX_ANGLE ||
                    Math.abs(angle.getDouble("roll")) > MAX_ANGLE) {
                result.put("angle", "角度不清请正视摄像头");
            } else {
                result.put("angle", "角度通过检测");
                successCount++;
            }

            // 4. 修改后的位置检查逻辑
            JSONObject location = face.getJSONObject("location");
            double left = location.getDouble("left");
            double top = location.getDouble("top");
            double width = location.getDouble("width");
            double height = location.getDouble("height");

            // 转换为相对坐标
            double normalizedLeft = left / imageWidth;
            double normalizedTop = top / imageHeight;
            double normalizedWidth = width / imageWidth;
            double normalizedHeight = height / imageHeight;

            double centerX = normalizedLeft + normalizedWidth / 2;
            double centerY = normalizedTop + normalizedHeight / 2;

            if (centerX < POSITION_THRESHOLD || centerX > (1 - POSITION_THRESHOLD) ||
                    centerY < POSITION_THRESHOLD || centerY > (1 - POSITION_THRESHOLD)) {
                result.put("location", "请保持人脸居中");
            } else {
                result.put("location", "位置通过检测");
                successCount++;
            }

            // 5. 检查配饰
            if (face.getJSONObject("glasses").getString("type").equals("none") &&
                    face.getJSONObject("mask").getInt("type") == 0) {
                result.put("accessories", "配饰检查通过");
                successCount++;

            } else {
                result.put("accessories", "请摘下配饰");
            }
            // 6. 检查遮挡
            JSONObject quality = face.getJSONObject("quality");
            JSONObject occlusion = quality.getJSONObject("occlusion");
            if (occlusion.getDouble("left_eye") > OCCLUSION_THRESHOLD ||
                    occlusion.getDouble("right_eye") > OCCLUSION_THRESHOLD ||
                    occlusion.getDouble("nose") > OCCLUSION_THRESHOLD ||
                    occlusion.getDouble("mouth") > OCCLUSION_THRESHOLD) {
                result.put("occlusion", "请勿遮挡人脸");
            } else {
                result.put("occlusion", "遮挡检查通过");
                successCount++;
            }
            // 7. 检查光照和模糊度
            double illumination = quality.getDouble("illumination");
            double blur = quality.getDouble("blur");

            if (illumination < MIN_ILLUMINATION || illumination > MAX_ILLUMINATION) {
                result.put("illumination", "光照过高或者图片不清晰，请更换拍摄地点重试");
            } else {
                result.put("illumination", "环境检查通过");
                successCount++;
            }
            if (blur > MAX_BLUR) {
                result.put("blur", "图片不清晰，请保持稳定");
            } else {
                result.put("blur", "模糊度检查通过");
                successCount++;
            }
            // 8. 检查双眼状态
            JSONObject eyeStatus = face.getJSONObject("eye_status");
            if (eyeStatus.getDouble("left_eye") < MIN_EYE_STATUS ||
                    eyeStatus.getDouble("right_eye") < MIN_EYE_STATUS) {
                result.put("eye_status", "请睁开双眼");
            } else {
                result.put("eye_status", "双眼状态检查通过");
                successCount++;
            }
            // 9. 检查人脸类型
            if (!face.getJSONObject("face_type").getString("type").equals("human")) {
                result.put("face_type", "非真人照片");
            } else {
                result.put("face_type", "人脸类型检查通过");
                successCount++;
            }
        if (faceResult.has("result") && faceResult.getJSONObject("result").getInt("face_num") > 0) {

            result.put("face_token", face.getString("face_token"));
        }
            // 返回结果
            result.put("success_count", successCount);
            result.put("total_checks", 10);
            return result;
        }
    private static JSONObject getJsonObject(String imageBase64) {
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        HashMap<String, Object> options = new HashMap<>();
        options.put("face_field", "age,gender,expression,emotion,face_type,mask,glasses,eye_status,quality,liveness");
        options.put("max_face_num", "10");
        options.put("face_type", "LIVE");
        options.put("liveness_control", "NORMAL");
        options.put("face_sort_type", 1);

        JSONObject faceResult = client.detect(imageBase64, "BASE64", options);
        return faceResult;
    }

}



